package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.Base;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.OutMainConfig;
import com.isunland.managesystem.entity.RInappMain;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.MyViewUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:  零购入库详情
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/7/18 14:34
 */
public class RetailInDetailFragment extends BaseFragment {

  @BindView(R.id.slv_minbillno) SingleLineView slvMinbillno;
  @BindView(R.id.slv_msupplyName) SingleLineView slvMsupplyName;
  @BindView(R.id.slv_materialKindName) SingleLineView slvMaterialKindName;
  @BindView(R.id.slv_storageName) SingleLineView slvStorageName;
  @BindView(R.id.slv_minappmanName) SingleLineView slvMinappmanName;
  @BindView(R.id.slv_minappmanDeptName) SingleLineView slvMinappmanDeptName;
  @BindView(R.id.slv_minappDate) SingleLineView slvMinappDate;
  @BindView(R.id.slv_mquamanName) SingleLineView slvMquamanName;
  @BindView(R.id.slv_mquaDate) SingleLineView slvMquaDate;
  @BindView(R.id.slv_invoiceNo) SingleLineView slvInvoiceNo;
  @BindView(R.id.slv_minCom) SingleLineView slvMinCom;
  @BindView(R.id.slv_remark) SingleLineView slvRemark;
  @BindView(R.id.slv_minbillStatusName) SingleLineView slvMinbillStatusName;
  @BindView(R.id.slv_regStaffName) SingleLineView slvRegStaffName;
  @BindView(R.id.slv_regDate) SingleLineView slvRegDate;
  @BindView(R.id.slv_mindealmanName) SingleLineView slvMindealmanName;
  @BindView(R.id.slv_mindealDate) SingleLineView slvMindealDate;
  @BindView(R.id.ll_retailIn) LinearLayout llRetailIn;

  private int REQUEST_STORAGE = 1;
  private int REQUEST_MQUAMAN = 2;
  private int REQUEST_APPMAN = 3;
  private int REQUEST_DELETE = 4;
  private int REQUEST_SUBMIT = 5;
  private int REQUEST_CUSTOMER = 6;
  private int REQUEST_MATERIAL = 7;

  private HashMap<String, OutMainConfig> mConfigMap;
  private RInappMain mainContent;
  private CallBack mcallBack;
  private int mtype;
  private int menuType;
  private int SAVE = 0;
  private int RUN = 1;
  private final int ADD = 2;
  private final int NEW = 3;
  private final int SUB = 4;
  private final int PUBLISH = 5;

  //回调接口
  public interface CallBack {
    void onRefresh(RInappMain content, int type);
  }

  @Override public void onAttach(Activity activity) {
    super.onAttach(activity);
    mcallBack = (CallBack) getActivity();
  }

  @Override public void onDetach() {
    super.onDetach();
    mcallBack = null;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    mainContent = (RInappMain) mBaseParams.getItem();
    mtype = mBaseParams.getType();
    if (BaseParams.TYPE_DETAIL == mtype) {
      //详情
      String dataStatus = mainContent.getMinbillStatusCode();
      if (DataStatus.NEW.equalsIgnoreCase(dataStatus) || DataStatus.ABORT.equalsIgnoreCase(
          dataStatus)) {
        menuType = NEW;
      } else if (DataStatus.WAIT_CHECK.equalsIgnoreCase(dataStatus)) {
        menuType = SUB;
      } else {
        menuType = PUBLISH;
      }
    }
    if (BaseParams.TYPE_ADD == mtype) {
      //添加
      menuType = ADD;
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (menuType) {
      //草稿状态：保存、保存并提交
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        menu.getItem(1).setTitle(R.string.submit);
        break;
      //草稿状态：保存、提交、删除
      case NEW:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      //提交状态：返回修改
      case SUB:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      //审核通过,已出库
      case PUBLISH:
        break;
      default:
        break;
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_save:
        //保存
        if (isCorrectInput()) {
          volleyPostSave(SAVE);
        }
        return true;
      case R.id.menu_item_submit:
        //保存并提交
        if (isCorrectInput()) {
          showDialog(BaseConfirmDialogFragment.newInstance(R.string.start_up_hint), REQUEST_SUBMIT);
        }
        return true;
      case R.id.menu_item_delete:
        //删除
        showDialog(BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm), REQUEST_DELETE);
        return true;
      case R.id.menu_item_stop:
        // 返回修改
        volleyPostAbort();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  /*判断必填项*/
  private boolean isCorrectInput() {
    if (slvMaterialKindName.getVisibility() == View.GONE
        || slvMaterialKindName.getVisibility() == View.VISIBLE && !TextUtils.isEmpty(
        slvMaterialKindName.getTextContent())) {
      return true;
    } else {
      ToastUtil.show(R.string.notComplete);
      return false;
    }
  }

  private void volleyPostSave(final int requestCode) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_IN_MIAN_SAVE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mainContent.getId());
    params.put("minbillno", mainContent.getMinbillno());
    params.put("minkindCode", mainContent.getMinkindCode());
    params.put("minkindName", mainContent.getMinkindName());

    params.put("msupplyName", mainContent.getMsupplyName());//供应商
    params.put("msupplyId", mainContent.getMsupplyId());//供应商

    params.put("materialKindCode", mainContent.getMaterialKindCode());//物料
    params.put("materialKindName", mainContent.getMaterialKindName());//物料

    params.put("storageName", mainContent.getStorageName());//仓库
    params.put("storageId", mainContent.getStorageId());//仓库id

    params.put("minappmanName", mainContent.getMinappmanName());//申办人
    params.put("minappmanId", mainContent.getMinappmanId());//申办人
    params.put("minappmanDeptName", mainContent.getMinappmanDeptName());//申办部门
    params.put("minappmanDeptCode", mainContent.getMinappmanDeptCode());//申办人
    params.put("minappDate", mainContent.getMinappDate());//申办时间

    params.put("mquamanName", mainContent.getMquamanName());//质检人
    params.put("mquamanId", mainContent.getMquamanId());//质检人
    params.put("mquaDate", mainContent.getMquaDate());//质检时间

    params.put("minbillStatusName", mainContent.getMinbillStatusName());//状态name
    params.put("minbillStatusCode", mainContent.getMinbillStatusCode());//状态code

    params.put("minCom", slvMinCom.getTextContent());//概要
    params.put("remark", slvRemark.getTextContent());//备注

    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(json, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          if (SAVE == requestCode) {
            //保存
            if (BaseParams.TYPE_ADD == mtype) {
              //跳转到物料列表界面tab
              getActivity().setResult(Activity.RESULT_OK);
              mcallBack.onRefresh(mainContent, BaseParams.TYPE_DETAIL);
            } else {
              ToastUtil.show(R.string.success_operation);
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
            }
          }
          if (RUN == requestCode) {
            volleyPostRun();
          }
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    });
  }

  private void volleyPostRun() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_IN_MIAN_RUN);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mainContent.getId());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  private void volleyPostAbort() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("runId", mainContent.getRunId().toString());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  //删除
  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RETAIL_IN_MIAN_DEL);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", mainContent.getId());
    params.put("deleteFormRecord", "true");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), getResponse());
  }

  public VolleyResponse getResponse() {
    return new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        SuccessMessage message = new Gson().fromJson(arg0, SuccessMessage.class);
        if (message.getResult() == null) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (message.getResult() != null && SuccessMessage.SUCCESS.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(R.string.success_operation);
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
        if (message.getResult() != null && SuccessMessage.FAILURE.equalsIgnoreCase(
            message.getResult())) {
          ToastUtil.show(message.getMessage());
        }
      }
    };
  }

  @Override protected int initLayoutId() {
    return R.layout.fragment_retail_in_detail;
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = super.onCreateView(inflater, container, savedInstanceState);
    ButterKnife.bind(this, rootView);
    //动态配置界面
    volleyPostConfig(rootView);
    return rootView;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    mConfigMap = new HashMap<>();
    slvMinbillno.setTextContent(mainContent.getMinbillno());
    slvMsupplyName.setTextContent(mainContent.getMsupplyName());
    slvMaterialKindName.setTextContent(mainContent.getMaterialKindName());
    slvStorageName.setTextContent(mainContent.getStorageName());
    slvMinappmanName.setTextContent(mainContent.getMinappmanName());
    slvMinappmanDeptName.setTextContent(mainContent.getMinappmanDeptName());
    slvMinappDate.setTextContent(mainContent.getMinappDate());
    slvMquamanName.setTextContent(mainContent.getMquamanName());
    slvMquaDate.setTextContent(mainContent.getMquaDate());
    slvInvoiceNo.setTextContent(mainContent.getInvoiceNo());
    slvMinCom.setTextContent(mainContent.getMinCom());
    slvRemark.setTextContent(mainContent.getRemark());
    slvMinbillStatusName.setTextContent(mainContent.getMinbillStatusName());
    slvRegStaffName.setTextContent(mainContent.getRegStaffName());
    slvRegDate.setTextContent(mainContent.getRegDate());
    slvMindealmanName.setTextContent(mainContent.getMindealmanName());
    slvMindealDate.setTextContent(mainContent.getMindealDate());

    //供应商
    slvMsupplyName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //跳转到客户名录列表界面
        Intent i = new Intent(getActivity(), CustomerListChooseActivity.class);
        startActivityForResult(i, REQUEST_CUSTOMER);
      }
    });

    //物料类别
    slvMaterialKindName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(new MaterielKindDialogFragment(), REQUEST_MATERIAL);
      }
    });

    //仓库
    slvStorageName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(new WareHouseDialogFragment(), REQUEST_STORAGE);
      }
    });

    //业务员
    slvMinappmanName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        Intent man = new Intent(getActivity(), SearchPersonActivity.class);
        man.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(man, REQUEST_APPMAN);
      }
    });

    //申办时间
    slvMinappDate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvMinappDate.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
                mainContent.setMinappDate(slvMinappDate.getTextContent());
              }
            }));
      }
    });
    //入库质检人
    slvMquamanName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        //Intent i = new Intent(getActivity(), AppointerListActivity.class);
        //startActivityForResult(i, REQUEST_MQUAMAN);
        Intent man = new Intent(getActivity(), SearchPersonActivity.class);
        man.putExtra(SearchPersonListFragment.EXTRA_FROM, SearchPersonListFragment.VALUE_COMMON);
        startActivityForResult(man, REQUEST_MQUAMAN);
      }
    });
    //入库质检时间
    slvMquaDate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        showDialog(BaseYMDTimeDialogFragment.newInstance(new Date())
            .setCallBack(new BaseYMDTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                slvMquaDate.setTextContent(MyDateUtil.format(date, MyDateUtil.TYPE_DATE));
                mainContent.setMquaDate(slvMquaDate.getTextContent());
              }
            }));
      }
    });
    if (SUB == menuType || PUBLISH == menuType) {
      MyViewUtil.setEnableAll(false, slvMaterialKindName.getTvContent(),
          slvMinbillno.getTvContent(), slvMsupplyName.getTvContent(),
          slvMaterialKindName.getTvContent(), slvStorageName.getTvContent(),
          slvMinappmanName.getTvContent(), slvMinappmanDeptName.getTvContent(),
          slvMinappDate.getTvContent(), slvMquamanName.getTvContent(), slvMquaDate.getTvContent(),
          slvInvoiceNo.getTvContent(), slvMinCom.getTvContent(), slvRemark.getTvContent(),
          slvMinbillStatusName.getTvContent(), slvRegStaffName.getTvContent(),
          slvRegDate.getTvContent(), slvMindealmanName.getTvContent(),
          slvMindealDate.getTvContent());
    }
  }

  private void volleyPostConfig(final View rootView) {
    String configUrl = ApiConst.getAbsoluteUrl(ApiConst.URL_OUT_MAIN_CONFIG);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("docKindCode", mainContent.getMinkindCode());//单据类别编码
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(configUrl, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        BaseOriginal<OutMainConfig> result =
            new Gson().fromJson(json, new TypeToken<BaseOriginal<OutMainConfig>>() {
            }.getType());
        ArrayList<OutMainConfig> mList = new ArrayList<>();
        if (Base.SUCCESS == result.getResult() && result.getRows() != null) {
          mList.addAll(result.getRows());
          mConfigMap = initConfigMap(mList);
          for (String tag : mConfigMap.keySet()) {
            SingleLineView lineView = (SingleLineView) rootView.findViewWithTag(tag);
            if (lineView != null) {
              OutMainConfig config = mConfigMap.get(tag);
              //设置显示和隐藏
              lineView.setVisibility(
                  "T".equalsIgnoreCase(config.getIfDisplayEdit()) ? View.VISIBLE : View.GONE);
              //设置标题
              lineView.setTextTitle(
                  (config.getFieldDesc().contains(":") || config.getFieldDesc().contains("："))
                      ? config.getFieldDesc() : MyStringUtil.connect(config.getFieldDesc(), "："));
              //设置是否可编辑,不可编辑可点击
              lineView.getTvContent().setFocusable("T".equalsIgnoreCase(config.getIfDisplay()));
              lineView.getTvContent().setClickable(true);
            }
          }
          llRetailIn.setVisibility(View.VISIBLE);
          MyUtils.dismissDialog();
        } else {
          ToastUtil.show("获取界面失败");
        }
      }
    });
  }

  private HashMap<String, OutMainConfig> initConfigMap(ArrayList<OutMainConfig> list) {
    HashMap<String, OutMainConfig> configMap = new HashMap<>();
    for (OutMainConfig item : list) {
      configMap.put(item.getFieldNameMap(), item);
    }
    return configMap;
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    //客户单位
    if (requestCode == REQUEST_CUSTOMER) {
      String customerName = data.getStringExtra(CustomerListChooseFragment.CUSTOMER_NAME);
      String customerId = data.getStringExtra(CustomerListChooseFragment.CUSTOMER_ID);
      slvMsupplyName.setTextContent(customerName);
      mainContent.setMsupplyName(customerName);
      mainContent.setMsupplyId(customerId);
      return;
    }
    if (requestCode == REQUEST_MATERIAL) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String materialKindName = customer.getName();
      String materialKindCode = customer.getId();
      slvMaterialKindName.setTextContent(materialKindName);
      mainContent.setMaterialKindCode(materialKindCode);
      mainContent.setMaterialKindName(materialKindName);
    }
    if (requestCode == REQUEST_STORAGE) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      String storageName = customer.getName();
      String storageId = customer.getId();
      slvStorageName.setTextContent(storageName);
      mainContent.setStorageId(storageId);
      mainContent.setStorageName(storageName);
    }
    if (requestCode == REQUEST_APPMAN || requestCode == REQUEST_MQUAMAN) {
      CustomerDialog man =
          (CustomerDialog) data.getSerializableExtra(SearchPersonListFragment.EXTRA_VALUE);
      String manName = man.getName();
      String manId = man.getId();
      if (requestCode == REQUEST_APPMAN) {
        //申请人
        slvMinappmanName.setTextContent(manName);
        slvMinappmanDeptName.setTextContent(man.getDept());
        mainContent.setMinappmanId(manId);
        mainContent.setMinappmanName(manName);
        mainContent.setMinappmanDeptCode(man.getMemberCode());//申请人部门code
        mainContent.setMinappmanDeptName(man.getDept());
      }
      if (requestCode == REQUEST_MQUAMAN) {
        //质检人
        slvMquamanName.setTextContent(manName);
        mainContent.setMquamanId(manId);
        mainContent.setMquamanName(manName);
      }
    }
    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      //保存并提交
      volleyPostSave(RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }
}
